import {notification, Upload, Button, Image } from 'antd';
import {UploadChangeParam, UploadFile} from 'antd/lib/upload/interface';
import {PlusOutlined, UploadOutlined} from '@ant-design/icons';
import style from './index.module.less';
import { ReactNode, useState, useEffect} from 'react';
import type { UploadProps } from 'antd';
export interface CustomUploadProps {
    onUploadSuccess?: (fileUrl: string,e: UploadFile<any>) => void;
    disabled?: boolean;
    accept?: string;
    children?: ReactNode;
    listType?: string;
    uploadType?: string;
    maxCount?: number;
    fileSize?: number;
    defaultFileList?: UploadFile[];
}
const UploadFiles = (props: CustomUploadProps & UploadProps) => {
    const {onUploadSuccess, disabled, accept = '.png,.jpg,.jpeg', maxCount = 1, children, 
      listType = "picture-card", uploadType = '', fileSize = 0, defaultFileList = [],
      action = "/cdwl-pay-base-service/file/upload"} = props;

    const baseUrl = import.meta.env.VITE_BASE_API;
    const [fileList, setFileList] = useState<UploadFile[]>([]);
    useEffect(() => {
      setFileList(defaultFileList)
    }, [defaultFileList])
    // 检查文件类型
    const checkFile = (file: UploadFile<any>): boolean => {
        const fileNameSplitList = file.name.split('.');
        const fileSuffix = '.' + fileNameSplitList[fileNameSplitList.length - 1];
        let message = '';
        if (!accept.split(',').includes(fileSuffix)) {
            message = '不支持此文件格式';
        }
        if (fileSize) {
            const isLt25M = file.size ? file.size / 1024 / 1024 < fileSize : true;
            if (!isLt25M) {
                message = `文件大小应小于${fileSize}M`;
            }
        }
        if (message) {
            notification.error({message});
        }
        return message ? false : true;
    };
    const handleChange = (data: UploadChangeParam<UploadFile<any>>) => {
      setFileList(data.fileList);
      if ( data.file && checkFile(data.file)) {
        if (data.file.status === "done") {
          if (data.file.response.code === 200) {
            onUploadSuccess && onUploadSuccess(data.file.response.data as string, data.file);
          } else {
            notification.error({ message: data.file.response.msg || "文件上传失败" })
            setFileList([])
          }
        }
      }
    };
    const onBeforeUpload = (file: UploadFile) => {
      return checkFile(file) || Upload.LIST_IGNORE;
    };

    const onRemove = (file: UploadFile) => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    }

    const [visible, setVisible] = useState(false)
    const [imgUrl, setImgUrl] = useState('')
    const onPreview = (file: UploadFile) => {
      if (listType === "text") {
        return
      }
      setVisible(true)
      if (file?.response?.code === 200) {
        setImgUrl(file.response.data)
      } else {
        setImgUrl(file.url || file.thumbUrl || "")
      }
    }

    const onVisibleChange = () => {
      setVisible(false)
    }


    return (
      <>
        <Upload className={style.upload}
                action = {baseUrl + action}
                accept={accept}
                multiple={true}
                disabled={disabled}
                showUploadList={true}
                listType={listType}
                maxCount={maxCount}
                fileList={fileList}
                defaultFileList={defaultFileList}
                beforeUpload={ onBeforeUpload }
                onChange={handleChange}
                onRemove={onRemove}
                onPreview={onPreview}
        >
          {fileList.length >= maxCount ? null : listType === "text" ? (<Button icon={<UploadOutlined />}>上传</Button>) : (<PlusOutlined />)}
        </Upload>
        <Image
          preview={{ visible: visible, onVisibleChange: onVisibleChange, src: imgUrl }}
          width={200}
          rootClassName={visible ? "" : style.previewImg}
        />
      </>
    );
};
export default UploadFiles;